<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\facade\Jpush;
use think\model\relation\BelongsTo;

class UserProductDiscount extends Base
{
    public static $_status = [
        '1' => '未使用',
        '2' => '已使用',
        '3' => '已过期',
    ];
    protected $name = 'user_product_discount';

    public static function getDiscount($uid, $pid)
    {
        try {
            return parent::where(['uid' => $uid, 'pid' => $pid, 'status' => 1, 'is_del' => 0])
                ->field('id,pid,amount')->select();
        } catch (\Exception $e) {
            return [];
        }
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'uid','id')->field('id,nickname,mobile,code');
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class, 'pid','id')->field('id,title,icon');
    }

    public function getStatusTextAttr($value, $data): string
    {
        return isset(self::$_status[$data['status']]) ? self::$_status[$data['status']] : '未知';
    }

    public function getExpireTimeAttr($value)
    {
        return $value ? date("Y-m-d H:i:s", $value) : '';
    }

    public function getUseTimeAttr($value)
    {
        return $value ? date("Y-m-d H:i:s", $value) : '';
    }

    public function getExpireDateAttr($value, $data)
    {
        return $data['expire_time'] ? date("Y-m-d", $data['expire_time']) : '';
    }

    public function getCreateDateAttr($value, $data)
    {
        return $data['create_time'] ? date("Y-m-d", $data['create_time']) : '';
    }

    /**
     * 抵扣券过期提醒
     * @return array
     */
    public static function expireNotify(): array
    {
        $time = time() - 604800;
        self::where('status', 1)->where('expire_time', '>', $time)->field('uid, explain')->select()->each(function ($upd){
            User::whereIn('id', $upd->uid)->where('registration_id', '<>', '')->field('id,registration_id')->select()->each(function ($item) use ($upd){
                $content = "温馨提醒：您的抵扣券【".$upd->explain."】即将到期，请尽快使用！";//点击跳转抵扣券列表
                $parameter = ['event_type'=>1001,'sub_event_type'=>1100];
                $extra = ['extras'=>['parameter'=>json_encode($parameter)]];

                Jpush::sendSingleNotify($item->registration_id, $content, $extra, $item->id);

                UserNotify::create([
                    'uid' => $item->id,
                    'type' => 6,
                    'title' => '抵扣券到期',
                    'content' => "您有抵扣券即将到期，请到【我的】—【抵扣券】查看使用"
                ]);
            });
        });

        return ['code' => 1, 'msg' => 'success'];
    }

    /**
     * 抵扣券过期
     * @return array
     */
    public static function expire(): array
    {
        self::where('status', 1)->where('expire_time', '<', time())->select()->each(function ($item){
            $item->status = 3;
            $item->save();
        });
        return ['code' => 1, 'msg' => 'success'];
    }
}
